import time
from selenium import webdriver
from selenium.webdriver.common.by import By

class WarehouseManagementTest:
    def __init__(self):
        self.driver = webdriver.Chrome()  # 使用Chrome浏览器驱动
        self.driver.get("http://localhost:8080/warehouse")  # 打开仓库管理系统页面

    def login(self):
        # 登录操作
        self.driver.find_element(By.ID, "username").send_keys("admin")
        self.driver.find_element(By.ID, "password").send_keys("password")
        self.driver.find_element(By.ID, "loginBtn").click()

    def add_product(self, product_name, quantity):
        # 添加产品操作
        self.driver.find_element(By.ID, "addProductBtn").click()
        self.driver.find_element(By.ID, "productName").send_keys(product_name)
        self.driver.find_element(By.ID, "quantity").send_keys(quantity)
        self.driver.find_element(By.ID, "saveBtn").click()

    def search_product(self, product_name):
        # 搜索产品操作
        self.driver.find_element(By.ID, "searchInput").send_keys(product_name)
        self.driver.find_element(By.ID, "searchBtn").click()

    def get_product_quantity(self, product_name):
        # 获取产品数量
        table = self.driver.find_element(By.ID, "productTable")
        rows = table.find_elements(By.TAG_NAME, "tr")
        for row in rows[1:]:  # 跳过表头
            cols = row.find_elements(By.TAG_NAME, "td")
            if cols[0].text == product_name:
                return int(cols[1].text)
        return None

    def test_warehouse_management(self):
        self.login()
        time.sleep(2)

        # 添加产品并验证
        product_name = "Product A"
        quantity = 10
        self.add_product(product_name, quantity)
        time.sleep(2)
        assert self.get_product_quantity(product_name) == quantity

        # 搜索产品并验证
        search_product_name = "Product B"
        self.search_product(search_product_name)
        time.sleep(2)
        assert self.get_product_quantity(search_product_name) is None

        self.driver.quit()

test = WarehouseManagementTest()
test.test_warehouse_management()
